<template>
  <div class="fault-process-container">
    <el-card shadow="never" class="search-card">
      <el-form :inline="true" :model="faultStore.searchForm" class="search-form" label-width="80px">
        <el-form-item label="设备名称">
          <!-- 根据设备列表加载状态和数据，合理渲染 el-select 或提示 -->
          <el-select
            v-if="deviceStore.deviceList && deviceStore.deviceList.length > 0" 
            v-model="faultStore.searchForm.deviceId"
            placeholder="请选择设备"
            filterable
            clearable
            :disabled="faultStore.loading"
          >
            <el-option
              v-for="item in deviceStore.deviceList" 
              :key="item.eqid"
              :label="item.eqname"
              :value="item.eqid"
            />
          </el-select>
          <!-- 如果设备列表正在加载，显示加载提示 -->
          <span v-else-if="deviceStore.loading" class="loading-text">正在加载设备列表...</span>
          <!-- 如果设备列表加载失败或为空，显示禁用输入框提示 -->
          <el-input v-else placeholder="设备列表加载失败或为空" disabled />
        </el-form-item>
        <el-form-item label="故障类型">
          <el-input v-model="faultStore.searchForm.faultType" placeholder="请输入故障类型" clearable :disabled="faultStore.loading" />
        </el-form-item>
        <el-form-item label="故障状态">
          <el-select v-model="faultStore.searchForm.status" placeholder="请选择" clearable :disabled="faultStore.loading">
            <el-option 
                v-for="(item, key) in faultStore.FaultStatusMap" 
                :key="key" 
                :label="item.label" 
                :value="key" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="紧急程度">
            <el-select v-model="faultStore.searchForm.severity" placeholder="请选择" clearable :disabled="faultStore.loading">
                <el-option 
                    v-for="(item, key) in faultStore.FaultSeverityMap" 
                    :key="key" 
                    :label="item.label" 
                    :value="key" 
                />
            </el-select>
        </el-form-item>
        <el-form-item label="报告人">
          <el-input v-model="faultStore.searchForm.reporter" placeholder="请输入报告人" clearable :disabled="faultStore.loading" />
        </el-form-item>
        <el-form-item label="处理人">
          <el-input v-model="faultStore.searchForm.handler" placeholder="请输入处理人" clearable :disabled="faultStore.loading" />
        </el-form-item>
        <el-form-item label="报告日期">
          <el-date-picker
            v-model="faultStore.searchForm.reportTimeRange" 
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 280px"
            clearable
            :disabled="faultStore.loading"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :disabled="faultStore.loading">查询</el-button>
          <el-button @click="handleResetSearch" :disabled="faultStore.loading">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card shadow="never" class="table-card">
      <div class="table-header">
        <el-button type="primary" @click="handleAddFault" :disabled="faultStore.loading || faultStore.formSubmitting">新增故障</el-button>
        <el-button 
            type="danger" 
            :disabled="selectedFaults.length === 0 || faultStore.loading || faultStore.formSubmitting" 
            @click="handleBatchDelete"
            :loading="faultStore.formSubmitting"
        >
          批量删除
        </el-button>
      </div>

      <el-table
        :data="faultList" 
        v-loading="faultStore.loading"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="faultId" label="故障ID" width="100" />
        <el-table-column prop="deviceName" label="关联设备" min-width="150" show-overflow-tooltip />
        <el-table-column prop="faultType" label="故障类型" width="120" />
        <el-table-column prop="faultDesc" label="故障描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="reportTime" label="报告时间" width="160" />
        <el-table-column prop="severity" label="紧急程度" width="100">
            <template #default="{ row }">
                <el-tag :type="faultStore.getFaultSeverityTagType(row.severity)">{{ row.severity }}</el-tag>
            </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
                <el-tag :type="faultStore.getFaultStatusTagType(row.status)">{{ row.status }}</el-tag>
            </template>
        </el-table-column>
        <el-table-column prop="reporter" label="报告人" width="100" />
        <el-table-column prop="handler" label="处理人" width="100" />
        <el-table-column prop="handleTime" label="处理时间" width="160" />
        <el-table-column prop="solution" label="解决方案" min-width="150" show-overflow-tooltip />
        <el-table-column prop="remark" label="备注" min-width="100" show-overflow-tooltip />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleViewDetail(row)">详情</el-button>
            <el-button type="warning" link @click="handleEditFault(row)" :disabled="faultStore.loading || faultStore.formSubmitting">处理/编辑</el-button>
            <el-button type="danger" link @click="handleDeleteFault(row.faultId)" :disabled="faultStore.loading || faultStore.formSubmitting">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="faultStore.searchForm.pageNo"
        v-model:page-size="faultStore.searchForm.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :small="false"
        :disabled="faultStore.loading || faultStore.formSubmitting"
        :background="true"
        layout="total, sizes, prev, pager, next, jumper"
        :total="faultStore.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 新增/编辑故障弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '处理/编辑故障' : '新增故障'"
      width="650px"
      :before-close="handleCloseDialog"
      destroy-on-close
    >
      <el-form
        :model="faultForm"
        :rules="faultFormRules"
        ref="faultFormRef"
        label-width="100px"
      >
        <el-row :gutter="20">
            <el-col :span="12">
                <el-form-item label="关联设备" prop="deviceId">
                    <el-select
                        v-if="deviceStore.deviceList && deviceStore.deviceList.length > 0"
                        v-model="faultForm.deviceId"
                        placeholder="请选择关联设备"
                        filterable
                        clearable
                        style="width: 100%;"
                        :disabled="isEdit" 
                    >
                        <el-option
                            v-for="item in deviceStore.deviceList"
                            :key="item.eqid"
                            :label="item.eqname"
                            :value="item.eqid"
                        />
                    </el-select>
                    <span v-else-if="deviceStore.loading" class="loading-text">正在加载设备列表...</span>
                    <el-input v-else placeholder="设备列表加载失败或为空" disabled />
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="故障类型" prop="faultType">
                    <el-input v-model="faultForm.faultType" placeholder="请输入故障类型" />
                </el-form-item>
            </el-col>
        </el-row>

        <el-form-item label="故障描述" prop="faultDesc">
          <el-input
            type="textarea"
            v-model="faultForm.faultDesc"
            :rows="3"
            placeholder="请输入详细故障描述"
          />
        </el-form-item>

        <el-row :gutter="20">
            <el-col :span="12">
                <el-form-item label="报告人" prop="reporter">
                    <el-input v-model="faultForm.reporter" placeholder="请输入报告人姓名" />
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="报告时间" prop="reportTime">
                    <el-date-picker>
                        v-model="faultForm.reportTime"
                        type="datetime"
                        placeholder="选择报告时间"
                        value-format="YYYY-MM-DD HH:mm:ss"
                        style="width: 100%"
                        :disabled="isEdit" <!-- 报告时间在编辑模式下通常不可更改 -->
                    </el-date-picker>
                </el-form-item>
            </el-col>
        </el-row>

        <el-row :gutter="20">
            <el-col :span="12">
                <el-form-item label="紧急程度" prop="severity">
                    <el-select v-model="faultForm.severity" placeholder="请选择紧急程度" style="width: 100%">
                        <el-option label="低" value="低" />
                        <el-option label="中" value="中" />
                        <el-option label="高" value="高" />
                        <el-option label="紧急" value="紧急" />
                    </el-select>
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="故障状态" prop="status">
                    <el-select v-model="faultForm.status" placeholder="请选择故障状态" style="width: 100%">
                        <el-option label="待处理" value="待处理" />
                        <el-option label="处理中" value="处理中" />
                        <el-option label="已解决" value="已解决" />
                        <el-option label="已关闭" value="已关闭" />
                    </el-select>
                </el-form-item>
            </el-col>
        </el-row>

        <el-divider v-if="isEdit" content-position="left">处理信息</el-divider>

        <el-row :gutter="20" v-if="isEdit">
            <el-col :span="12">
                <el-form-item label="处理人" prop="handler">
                    <el-input v-model="faultForm.handler" placeholder="请输入处理人姓名" />
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="处理时间" prop="handleTime">
                    <el-date-picker
                        v-model="faultForm.handleTime"
                        type="datetime"
                        placeholder="选择处理完成时间"
                        value-format="YYYY-MM-DD HH:mm:ss"
                        style="width: 100%"
                        :disabled="!['已解决', '已关闭'].includes(faultForm.status)"
                    />
                </el-form-item>
            </el-col>
        </el-row>

        <el-form-item label="解决方案" prop="solution" v-if="isEdit">
          <el-input
            type="textarea"
            v-model="faultForm.solution"
            :rows="3"
            placeholder="请输入故障解决方案"
          />
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input
            type="textarea"
            v-model="faultForm.remark"
            :rows="2"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCloseDialog" :disabled="faultStore.formSubmitting">取消</el-button>
          <el-button type="primary" @click="handleSubmitForm" :loading="faultStore.formSubmitting">
            {{ isEdit ? '保存处理' : '新增' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, onMounted, computed, watch, ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useFaultStore } from '@/stores/modules/fault';
import { useDeviceStore } from '@/stores/modules/device';
import { storeToRefs } from 'pinia';

const faultStore = useFaultStore();
const deviceStore = useDeviceStore();

// 使用 storeToRefsM解构响应式状态，保持响应性
const { 
    faultList, 
    loading, 
    total, 
    faultForm, 
    selectedFaults, 
    dialogVisible, 
    isEdit, 
    formSubmitting 
} = storeToRefs(faultStore);

const faultFormRef = ref(null); // 用于访问 ElForm 组件实例

// 组件挂载时，优先加载设备列表，再加载故障列表
onMounted(async () => {
    // 优先加载所有设备列表，给 el-select 提供选项
    // pageSize 设置为足够大，确保获取所有设备
    await deviceStore.fetchDeviceList({ pageNo: 1, pageSize: 99999 }); 
    // 然后再加载故障列表，此时 deviceStore.deviceList 已经有数据了
    await fetchFaultList(); 
});

/**
 * 从后端获取故障列表数据
 */
const fetchFaultList = async () => {
    try {
        await faultStore.fetchFaultList(faultStore.searchForm);
    } catch (error) {
        console.error('获取故障列表失败:', error);
        // ElMessage 在 store 层面已处理，这里无需重复提示
    }
};

/**
 * 处理搜索按钮点击事件
 */
const handleSearch = () => {
  faultStore.searchForm.pageNo = 1; // 搜索时重置为第一页
  fetchFaultList();
};

/**
 * 处理重置搜索按钮点击事件
 */
const handleResetSearch = () => {
  faultStore.resetSearchForm(); // 重置搜索表单状态
  handleSearch(); // 执行搜索以刷新列表
};

/**
 * 处理表格多选变化事件
 * @param {Array} val - 当前选中的行数据数组
 */
const handleSelectionChange = (val) => {
  faultStore.updateSelectedFaults(val);
};

/**
 * 处理每页显示条数变化事件
 * @param {number} size - 新的每页显示条数
 */
const handleSizeChange = (size) => {
  faultStore.searchForm.pageSize = size;
  faultStore.searchForm.pageNo = 1; // 改变每页条数时回到第一页
  fetchFaultList();
};

/**
 * 处理当前页码变化事件
 * @param {number} page - 新的当前页码
 */
const handleCurrentChange = (page) => {
  faultStore.searchForm.pageNo = page;
  fetchFaultList();
};

// 故障表单校验规则
const faultFormRules = reactive({
  deviceId: [{ required: true, message: '请选择关联设备', trigger: 'change' }],
  faultType: [{ required: true, message: '请输入故障类型', trigger: 'blur' }],
  faultDesc: [{ required: true, message: '请输入故障描述', trigger: 'blur' }],
  reporter: [{ required: true, message: '请输入报告人', trigger: 'blur' }],
  reportTime: [{ required: true, message: '请选择报告时间', trigger: 'change' }],
  severity: [{ required: true, message: '请选择紧急程度', trigger: 'change' }],
  status: [{ required: true, message: '请选择故障状态', trigger: 'change' }],
  handler: [
    { 
        validator: (rule, value, callback) => {
            // 当状态为 '处理中', '已解决', '已关闭' 时，处理人必填
            if (['处理中', '已解决', '已关闭'].includes(faultForm.value.status)) {
                if (!value) {
                    callback(new Error('处理中/已解决/已关闭状态下，处理人不能为空'));
                } else {
                    callback();
                }
            } else {
                callback(); // 其他状态下不校验
            }
        }, 
        trigger: 'blur'
    }
  ],
  solution: [
    { 
        validator: (rule, value, callback) => {
            // 当状态为 '已解决', '已关闭' 时，解决方案必填
            if (['已解决', '已关闭'].includes(faultForm.value.status)) {
                if (!value) {
                    callback(new Error('已解决/已关闭状态下，解决方案不能为空'));
                } else {
                    callback();
                }
            } else {
                callback(); // 其他状态下不校验
            }
        }, 
        trigger: 'blur'
    }
  ]
});

// 监听故障状态变化，自动填充处理时间或清空相关字段
watch(() => faultForm.value.status, (newStatus, oldStatus) => {
    // 仅在编辑模式下处理
    if (isEdit.value) {
        // 如果新状态是已解决或已关闭，且处理时间为空，则自动填充当前时间
        if (['已解决', '已关闭'].includes(newStatus)) {
            if (!faultForm.value.handleTime) {
                faultForm.value.handleTime = new Date().toISOString().slice(0, 19).replace('T', ' '); 
            }
        }
        // 如果旧状态是已解决或已关闭，新状态不是，则清空处理时间和解决方案，避免数据残留
        if (
            oldStatus && // 确保有旧状态（避免初始化时触发）
            ['已解决', '已关闭'].includes(oldStatus) &&
            !['已解决', '已关闭'].includes(newStatus)
        ) {
            faultForm.value.handleTime = '';
            faultForm.value.solution = '';
            // 同时清除相关字段的校验状态
            if (faultFormRef.value) {
                faultFormRef.value.clearValidate(['handler', 'solution']);
            }
        }
    }
});


/**
 * 处理新增故障按钮点击事件
 */
const handleAddFault = () => {
  faultStore.isEdit = false; // 设置为新增模式
  faultStore.resetFaultForm(); // 重置表单为空，并设置默认值
  faultStore.faultForm.reportTime = new Date().toISOString().slice(0, 19).replace('T', ' '); // 预设报告时间为当前时间
  faultStore.dialogVisible = true; // 显示弹窗
  nextTick(() => { // 确保 DOM 更新后清除校验
    if (faultFormRef.value) {
      faultFormRef.value.clearValidate();
    }
  });
};

/**
 * 处理编辑/处理故障按钮点击事件
 * @param {Object} row - 当前行数据
 */
const handleEditFault = (row) => {
  faultStore.isEdit = true; // 设置为编辑模式
  // 深度复制行数据到表单，防止直接修改表格数据，并保持响应性
  faultStore.faultForm = { ...row }; 
  faultStore.dialogVisible = true; // 显示弹窗
  nextTick(() => { // 确保 DOM 更新后清除校验
    if (faultFormRef.value) {
      faultFormRef.value.clearValidate();
    }
  });
};

/**
 * 提交新增/编辑故障表单
 */
const handleSubmitForm = async () => {
  if (!faultFormRef.value) return;
  try {
    await faultFormRef.value.validate(); // 执行表单校验
    // 根据是新增还是编辑调用不同的 Store action
    if (isEdit.value) {
      await faultStore.updateFault(); 
    } else {
      await faultStore.addFault(); 
    }
    // 成功提示和弹窗关闭在 Store 中处理，这里只需处理验证失败的情况
  } catch (error) {
    if (error === false) { 
      ElMessage.error('表单验证失败，请检查输入项。');
      console.error('Form validation failed:', error);
    } else { 
      // 其他未知错误由 Store 处理
      console.error('提交表单操作异常:', error);
    }
  } 
};

/**
 * 关闭弹窗前的回调
 */
const handleCloseDialog = () => {
  faultStore.dialogVisible = false; // 隐藏弹窗
  faultStore.resetFaultForm(); // 重置 Store 中的表单数据
  // 确保表单组件的校验状态也重置，如果用户在没提交的情况下关闭
  nextTick(() => { // 确保 DOM 更新后重置字段和校验
    if (faultFormRef.value) {
      faultFormRef.value.resetFields(); 
      faultFormRef.value.clearValidate(); // 再次清除以防万一
    }
  });
};

/**
 * 删除单个故障工单
 * @param {number} faultId - 故障工单的ID (前端ID)
 */
const handleDeleteFault = async (faultId) => { 
  try {
    await ElMessageBox.confirm(
      `确定要删除故障ID为 "${faultId}" 的工单吗？此操作不可逆！`, 
      '警告', // 更改标题为“警告”
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );
    await faultStore.deleteFault(faultId); 
    // 成功和失败提示在 store 中处理
  } catch (error) {
    if (error === 'cancel') {
      ElMessage.info('已取消删除操作。');
    } else {
      console.error('删除故障操作在组件层捕获到错误:', error);
      // 其他错误由 Store 处理
    }
  }
};

/**
 * 批量删除故障工单
 */
const handleBatchDelete = async () => {
  if (selectedFaults.value.length === 0) {
    ElMessage.warning('请选择要删除的故障工单。');
    return;
  }
  const faultIds = selectedFaults.value.map(f => f.faultId); 
  // 限制显示ID的数量，避免弹窗过长
  const faultIdsDisplay = faultIds.length > 5 ? faultIds.slice(0, 5).join('，') + '...等' : faultIds.join('，');

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedFaults.value.length} 条故障工单（ID: ${faultIdsDisplay}）吗？此操作不可逆！`, 
      '警告', 
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );
    await faultStore.deleteFaults(faultIds); 
    // 成功、部分成功、失败提示在 Store 中处理
  } catch (error) {
    if (error === 'cancel') {
      ElMessage.info('已取消批量删除操作。');
    } else {
      console.error('批量删除故障操作在组件层捕获到错误:', error);
      // 其他错误由 Store 处理
    }
  }
};

/**
 * 查看故障详情
 * @param {Object} row - 当前行数据
 */
const handleViewDetail = async (row) => {
  try {
    const detail = await faultStore.fetchFaultDetail(row.faultId);

    // 动态生成 ElMessageBox 的内容，包含样式
    ElMessageBox.alert(`
    <style>
      .fault-detail-content { font-size: 14px; line-height: 1.8; }
      .fault-detail-content p { margin-bottom: 8px; display: flex; align-items: flex-start; }
      .fault-detail-content strong { flex-shrink: 0; width: 100px; text-align: right; margin-right: 15px; color: #606266; }
      .fault-detail-content span { flex-grow: 1; word-break: break-all; }
      .detail-tag { font-weight: bold; font-size: 16px; }
      /* 自定义颜色映射，与 TagType 保持一致 */
      .tag-type-danger { color: #F56C6C; }
      .tag-type-warning { color: #E6A23C; }
      .tag-type-success { color: #67C23A; }
      .tag-type-info { color: #909399; }
      .tag-type-default { color: #303133; } /* 默认颜色 */
    </style>
    <div class="fault-detail-content">
      <p><strong>故障ID:</strong> <span>${detail.faultId || 'N/A'}</span></p>
      <p><strong>关联设备:</strong> <span>${detail.deviceName || 'N/A'} (ID: ${detail.deviceId || 'N/A'})</span></p>
      <p><strong>故障类型:</strong> <span>${detail.faultType || 'N/A'}</span></p>
      <p><strong>故障描述:</strong> <span>${detail.faultDesc || '无'}</span></p>
      <p><strong>报告时间:</strong> <span>${detail.reportTime || 'N/A'}</span></p>
      <p><strong>紧急程度:</strong> <span class="detail-tag tag-type-${faultStore.getFaultSeverityTagType(detail.severity) || 'default'}">${detail.severity || 'N/A'}</span></p>
      <p><strong>故障状态:</strong> <span class="detail-tag tag-type-${faultStore.getFaultStatusTagType(detail.status) || 'default'}">${detail.status || 'N/A'}</span></p>
      <p><strong>报告人:</strong> <span>${detail.reporter || 'N/A'}</span></p>
      <p><strong>处理人:</strong> <span>${detail.handler || '未指定'}</span></p>
      <p><strong>处理时间:</strong> <span>${detail.handleTime || '未处理'}</span></p>
      <p><strong>解决方案:</strong> <span>${detail.solution || '无'}</span></p>
      <p><strong>备注:</strong> <span>${detail.remark || '无'}</span></p>
    </div>
  `, `故障 "${detail.faultId}" 详情`, {
    dangerouslyUseHTMLString: true, // 允许渲染 HTML 字符串
    confirmButtonText: '关闭',
    customClass: 'fault-detail-messagebox', // 自定义类名以便外部样式覆盖
  });
  } catch (error) {
    console.error('查看故障详情失败:', error);
    // ElMessage 在 store 层面已处理，这里无需重复提示
  }
};
</script>

<style scoped>
.fault-process-container {
  padding: 20px;
  background-color: var(--el-bg-color-page);
}

.search-card,
.table-card {
  margin-bottom: 20px;
  border-radius: 8px; /* 增加圆角 */
}

.search-form {
  padding-bottom: 0;
}
.el-form-item {
  margin-bottom: 18px; /* 保持与 Element Plus 默认间距一致 */
}

/* 针对设备列表加载状态的文本样式 */
.loading-text {
  color: var(--el-text-color-secondary);
  font-size: 13px;
  line-height: 32px; /* 和 input 高度保持一致 */
  height: 32px;
  display: inline-block;
  vertical-align: middle;
}

.table-header {
  display: flex;
  justify-content: flex-start;
  margin-bottom: 15px;
}

.table-header .el-button {
  margin-right: 10px;
}

.el-pagination {
  margin-top: 20px;
  justify-content: flex-end;
}

.el-divider {
  margin: 20px 0;
}

/* 针对详情弹窗的样式 */
/* 注意：ElMessageBox 的 customClass 样式可能需要全局定义或使用深度选择器 */
/* 如果在 scoped style 中定义，需要使用 ::v-deep 或 :deep() */
:deep(.fault-detail-messagebox) {
  width: 650px;
  max-width: 90%; /* 响应式考虑 */
  border-radius: 8px;
}

:deep(.fault-detail-messagebox .el-message-box__content) {
  max-height: 50vh; /* 限制内容区域高度 */
  overflow-y: auto; /* 超出则滚动 */
  padding: 15px 20px; /* 内部边距 */
}

/* 保持 el-tag 在表格中的默认样式 */
.el-table .el-tag {
    vertical-align: middle;
}
</style>
